<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Crud extends Model{
	/* 创建数组传递给视图 */
	var $data = array();
	var $form = array();
	var $controller;
	/* 调用构造函数 */
	
	function Crud()
	{
		parent::Model();
		$this->load->helper('form');
		$this->load->helper('url');
		$this->load->library('validation');
		$this->load->model('display');
		// 建立映射表单
		$this->form = array(		
		// 页面表映射		
		'page'=> array(
		'id'=> array('label','readonly','integer',''),
		'title'=> array('label','input','required',''),
		'heading'=> array('label','input','required',''),
		'content'=> array('label','textarea','required',''),		
		'posted'=> array('label','input','required',''),	
		),	
		// 分组表映射		
		'group'=> array(
		'id'=> array('Group ID','readonly','integer',''),
		'name'=> array('Group Name','input','required',''),
		'description'=> array('Description','input','required',''),
		'created'=> array('Create Time','timestamp','required',''),
		'modified'=> array('Modifiy Time','updatestamp','required',''),
		),
		// 用户表映射		
		'user'=> array(
		'id'=> array('User ID','readonly','integer',''),
		'username'=> array('User Name','input','required','must be needed'),
		'password'=> array('Password','input','required','must be needed'),
		'group_id'=> array('Group','dropdown','numeric','group'),
		'first_name'=> array('First Name','input','required',''),
		'last_name'=> array('Last Name','input','required',''),
		'email'=> array('Email','input','required','must be needed'),
		'id_card'=> array('ID Card','input','required','must be needed'),
		'cell_phone'=> array('Cell Phone','input','required','must be needed'),
		'created'=> array('Create Time','timestamp','required','must be needed'),
		'modified'=> array('Modifiy Time','updatestamp','required','must be needed'),	
		'status'=> array('Status','dropdown','','user_status'),	
		),	
		// TODO:更多的表映射		
		);
	}
	/* 管理所有数据 */
	
	function manage($controller='', $fields = '', $message = '', $test ='no')
	{
		$result = '';
		$mysess = $this->session->userdata('session_id');
		$mystat = $this->session->userdata('status');
		if(!$this->db->table_exists($controller)){
			$message = 'Table is not exist.';
			return $message;
		}
		else{
			$this->db->select('id, name');
			$query = $this->db->get($controller);
			if ($query->num_rows() > 0){
				
			}
			else{
				
			}
			
			
		}
	}
	/* 获取所有数据 */
	
	function read($controller='', $fields = '', $message = '', $test ='no', $view='',$header='')
	{
		if(!$this->db->table_exists($controller))
		{
			$message = 'Table is not exist.';
			return $message;
		}
		else{
			$this->db->select($fields);
			$query = $this->db->get($controller);
			if ($query->num_rows()> 0)
			{
				$result = $query->result();
			}
			else{
				$message = 'No data.';
				return $message;
			}
		}
		$mytable ="";
		$this->load->library('table');
		$this->table->set_heading($header);	
		$tpl = $this->set_template();
		$this->table->set_template($tpl);	
		foreach($result as $row)
			{			
			$row_array = (array)$row;
			//var_dump($row_array);
			foreach($row_array as $key=>$value)
			{
				switch($key){
					case 'id':
					$row_vars[]="$value</td>";	
					$id = $value;						
					break;
					case 'name':
					$row_vars[]="<td><strong>$value</strong></td>";
					break;
					case 'description':
					$row_vars[]="<td class='tags column-tags'>$value</td>";
					break;
					case 'created':
					$row_vars[]="<td class='date column-date'>$value</td>";
					break;
					case 'modified':
					$row_vars[]="<td class='date column-date'>$value</td>";
					break;
					default:
					break;
				}
				
			}	
			$view = $controller."_view";
			$row_vars[]="<td><a href='$controller/$view/$id'>View Detail</a>";				
			$content = join("",$row_vars);			
			$this->table->add_row($content);
			$row_vars = array();			
			}		
		$mytable = $this->table->generate();
		$data['mycontent'] = $mytable; 		
		//加载通用表单视图		
		$this->display->content($view,$data);
		$this->load->view('base/footer_view');		
	}
	
	//设置表格模板
	function set_template(){
		$template = array();
		$template['table_open']="<table class='widefat fixed' cellspacing='0'>";
		$template['heading_row_start']="<tr class='manage-column column-title'>";
		$template['heading_row_end']="</tr>";	
		
		$template['row_start']="<tr class='alternate author-self status-publish iedit' valign='top'>";
		$template['row_end']="</tr>";
		
		$template['row_alt_start']="<tr class='' valign='top'>";
		$template['row_alt_end']="</tr>";	
		
		return $template;		
	}
	/* 删除一条数据 */
	
	function delete($controller, $id, $state='no', $test='no')
	{
	}
	/* 尝试删除一条数据 */
	
	function try_delete($controller, $id,$test='no')
	{
	}
	/* 插入或者更新一条数据 */
	
	function save($controller, $id, $test='no',$view)
	{
		$myform = ''; 
		$myid = 0;
		$current_value = array();
		//检查表是否存在
		if(!$this->db->table_exists($controller))
		{
			return FALSE;
		}
		else{
			//do nothing
		}
		//检查是否有id数据,若有便更新记录
		if(isset($id)&&$id>0)
		{
			$myid = $id;
			$this->db->where('id', $id);
			$query = $this->db->get($controller);			
			if ($query->num_rows() > 0)
			{
				$row = $query->row();
				foreach($row as $key =>$value)
				{
					$_POST[$key] = $this->validation->$key;
					if(isset($_POST[$key]))
					{
						$current_value[$key] = $_POST[$key];
					}
					else{
						$current_value[$key] = $value;
					}
					}	
			}
			else{
				//do nothing			
				}			
		}
		//若无则加入新的记录
		else{			
			if(isset($_POST))
			{
				foreach($_POST as $key => $value)
				{
					if(isset($_POST[$key]))
					{
						$current_value[$key] = $_POST[$key];
					}
					else{
						//do nothing.
						}    
					}  
			}
			else{
				//do nothing
				} 
		}
		//构造通用表单录入模块
		$myform .= form_open("$controller/interim");
		$myform .= "<table class='form-table'>";		
		$myform .= "<p>".$this->validation->error_string."</p>";
		//生成通用表单
		foreach($this->form[$controller] as $key => $value)
		{
			$field_label = $value[0];
			$field_type = $value[1];
			$field_rule = $value[2];
			$field_helper = $value[3];
			if('required'==$field_rule)
			{
				$class = "form-field form-required";
			}
			else{
				$class = "form-field";
			}
			switch($field_type)
			{
				//文本框
				case 'input':
				$data = array(
				'name'=>$key,
				'id'=>$key,
				'value'=>$current_value[$key],				
				);
				$myform .="<tr class=\"".$class."\">";
				$myform .= "<th scope=\"row\">".form_label($field_label,$key)."</th>"; 
				$myform .= "<td>";
				$myform .= form_input($data);
				$myform .= "</td></tr>";
				break;
				//文本域
				case 'testarea':
				$data = array();
				break;
				//下拉列表
				case 'dropdown':
				$dropbox = array();
				if(isset($value[3]))
				{
					$temptable = $value[3];  
					$this->db->select('id, name');
					$query = $this->db->get($temptable);
					if ($query->num_rows() > 0)
					{
						foreach ($query->result() as $row)
						{
							$dropbox[$row->id] = $row->name;
						}
					}
					else{
						//do nothing
					}
				}
				else{
					//do nothing
				}
				$myform .= "<tr><td valign='top'>$value[0]</td><td>";
				$myform .= form_dropdown($key, $dropbox, $current_value[$key]);
				$myform .= "</td></tr>";
				break;
				//隐藏域
				case 'hidden':
				$data = array();
				break;
				//只读域
				case 'readonly':
				$myform .="<tr class=\"".$class."\">";
				$myform .= "<th scope=\"row\">".form_label($field_label.$field_desc,$key)."</th>";
				$myform .= "<td>";
				$myform .= form_hidden($key, $current_value[$key]);  
				$myform .= "</td></tr>";
				break;
				//创建时间戳
				case 'timestamp':				
				$myform .="<tr class=\"".$class."\">";
				$myform .= "<th scope=\"row\">".form_label($field_label.$field_desc,$key)."</th>";
				$myform .= "<td>";	
				$now = time(); 			 
				if(''==$current_value[$key]||NULL==$current_value[$key]){
					$time = date("Y-m-d H:i:s",$now);
				}
				else{
					$time = date("Y-m-d H:i:s",$current_value[$key]);
					}  
				$myform .= form_input($key, $time);
				$myform .= "</td></tr>";
				break;
				//更新时间戳
				case 'updatestamp':
				$myform .="<tr class=\"".$class."\">";
				$myform .= "<th scope=\"row\">".form_label($field_label.$field_desc,$key)."</th>";
				$myform .= "<td>";	
				$now = time(); 
				$time = date("Y-m-d H:i:s",$now);			 
				$myform .= form_input($key, $time);
				$myform .= "</td></tr>";
				break;
				case 'checkbox':
				//复选域
				$data = array(
				'name'=>$key,
				'id'=>$key,
				'value'=>$current_value[$key],	
				'checked'=>'checked',
				
				);
				$myform .="<tr class=\"".$class."\">";
				$myform .= "<th scope=\"row\">".form_label($field_label,$key)."</th>"; 
				$myform .= "<td>";
				$myform .= form_checkbox($data);
				$myform .= "</td></tr>";
				break;				
				//默认操作
				default:
				break;
			}
		}
		$myform .= form_close();
		$myform .= "</table>";
		//提交域
		$myform .= "<p class=\"submit\">"; 
		$myform .= form_submit('submit','Submit',"class='button-primary'");
		$myform .= "</p>";
		$data['mycontent'] = $myform; 		
		//加载通用表单视图		
		$this->display->content($view,$data);
		$this->load->view('base/footer_view');	
	}
	//  插入数据	
	function insert($controller, $newpost, $test = 'no',$view)
	{
		$myform = '';
		if(!$this->db->table_exists($controller)){
			//test here!
			} 
		else{
			//do nothing.
			}				
		$_POST = $newpost;
		unset($_POST['submit']);
		$errorform = '';
		$newtemparray = $this->form[$controller];
		foreach($newtemparray as $key => $value){			
			$field_label = $value[0];
			$field_type = $value[1];
			$field_rule = $value[2];
			$field_helper = $value[3];
			//
			$fields[$key]= $field_label;
			$rules[$key]= $field_rule;			
		}
		$this->validation->set_rules($rules);
		$this->validation->set_fields($fields); 
		//验证失败返回前页
		if (FALSE == $this->validation->run()){
			$id = $_POST['id'];
			$this->save($controller, $id, 'no',$view);
		}
		//验证通过
		else
		{
			//已有id则更新
			if(isset($_POST['id']) && $_POST['id'] > 0) 
			{
				$tempid = $_POST['id'];
				unset($_POST['id']);
				$this->db->where('id', $tempid);
				$this->db->update($controller, $_POST); 
				if(1 == $this->db->affected_rows()){
				}
				else{
					}  
				
			}
			//若无则新建
			else{
				$this->db->insert($controller, $_POST);
				if(1==$this->db->affected_rows()){
				}
				else{
				}
			}
		}
	}
}
?>